import React, {useState} from 'react';
import {Button, Form, Input, Modal, Pagination, Space, Table, Tag} from 'antd';
import type {ColumnsType} from 'antd/es/table';
import {DeleteOutlined, EditOutlined, SearchOutlined} from '@ant-design/icons';
import UserForm from "./components/UserForm";
import {getUserList} from '../../api/user'

const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    getCheckboxProps: (record: DataType) => ({
        disabled: record.name === 'Disabled Index',
        // Column configuration not to be checked
        name: record.name,
    }),
};

interface DataType {
    key: string;
    name: string;
    age: number;
    address: string;
    tags: string[];
}

const data: DataType[] = [
    {
        key: '1',
        name: 'John Brown',
        age: 32,
        address: 'New York No. 1 Lake Park',
        tags: ['nice', 'developer'],
    },
    {
        key: '2',
        name: 'Jim Green',
        age: 42,
        address: 'London No. 1 Lake Park',
        tags: ['loser'],
    },
    {
        key: '3',
        name: 'Joe Black',
        age: 32,
        address: 'Sydney No. 1 Lake Park',
        tags: ['cool', 'teacher'],
    },
    {
        key: '4',
        name: 'John Brown',
        age: 32,
        address: 'New York No. 1 Lake Park',
        tags: ['nice', 'developer'],
    },
    {
        key: '5',
        name: 'Jim Green',
        age: 42,
        address: 'London No. 1 Lake Park',
        tags: ['loser'],
    },
    {
        key: '6',
        name: 'Joe Black',
        age: 32,
        address: 'Sydney No. 1 Lake Park',
        tags: ['cool', 'teacher'],
    },

];
const Index: React.FC = () => {
    const [users, setUsers] = useState(data)
    const [open, setOpen] = useState(false);
    const [title, setTile] = useState<String>();
    const [rowData, setRow] = useState(null);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [page, setPage] = useState({pageNum: 1, pageSize: 10});
    // 渲染table和分页
    getUserList(page).then((res: any) => {
        setUsers(res);
        setPage({pageNum: res.pageNum, pageSize: res.pageSize});
    })
    const getList = async () => {
        const res = await getUserList({page: "1"})
    }
    const showModal = (title: String, record: any) => {
        setRow(record);
        setTile(title);
        setOpen(true);
    };

    const handleOk = () => {
        setConfirmLoading(true);
        setTimeout(() => {
            setOpen(false);
            setConfirmLoading(false);
        }, 2000);
    };

    const handleCancel = () => {
        console.log('Clicked cancel button');
        setOpen(false);
    };

    const onFinish = (values: any) => {
        console.log('Success:', values);
    };

    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };
    const columns: ColumnsType<DataType> = [
        {
            title: 'Name',
            dataIndex: 'name',
            key: 'name',
            render: (text: String) => <a>{text}</a>,
        },
        {
            title: 'Age',
            dataIndex: 'age',
            key: 'age',
        },
        {
            title: 'Address',
            dataIndex: 'address',
            key: 'address',
        },
        {
            title: 'Tags',
            key: 'tags',
            dataIndex: 'tags',
            render: (tags: string[]) => (
                <span>
        {tags.map((tag) => {
            let color = tag.length > 5 ? 'geekblue' : 'green';
            if (tag === 'loser') {
                color = 'volcano';
            }
            return (
                <Tag color={color} key={tag}>
                    {tag.toUpperCase()}
                </Tag>
            );
        })}
      </span>
            ),
        },
        {
            title: 'Action',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button type={"primary"} ghost icon={<EditOutlined/>}
                            onClick={() => showModal('修改', record)}>Edit</Button>
                    <Button type={"primary"} danger ghost icon={<DeleteOutlined/>}>Delete</Button>
                </Space>
            ),
        },
    ];
    return (
        <div>
            <div style={{paddingBottom: '20px'}}>
                <Form layout={"inline"}>
                    <Form.Item
                        label="姓名"
                        name="name"
                    >
                        <Input name={'name'} style={{width: 180}} placeholder={'请输入需要搜索是关键词'}/>
                    </Form.Item>
                    <Form.Item>
                        <Input name={'name'} style={{width: 180, marginLeft: 10}}
                               placeholder={'请输入需要搜索是关键词'}/>
                    </Form.Item>
                    <Form.Item>
                        <Button name={'search'} icon={<SearchOutlined/>}>搜索</Button>
                        <Button type={"primary"} danger name={'reset'} style={{marginLeft: 10}}
                                icon={<SearchOutlined/>}>重置</Button>
                    </Form.Item>
                </Form>
            </div>
            <div style={{paddingBottom: '20px'}}>
                <Button type={"primary"} onClick={() => showModal('添加', null)}>add</Button>
                <Button type={"primary"} style={{
                    marginLeft: '20px'
                }}>delete</Button>
            </div>
            <Table columns={columns} rowSelection={{
                type: 'checkbox',
                ...rowSelection,
            }} dataSource={users} pagination={false}/>
            <Pagination
                total={85}
                showSizeChanger
                showQuickJumper
                current={page.pageNum}
                pageSize={page.pageSize}
                showTotal={(total) => `总共 ${total} 条`}
            />
            <UserForm title={title}
                      open={open}
                      onFinish={onFinish}
                      onFinishFailed={onFinishFailed}
                      handleCancel={handleCancel}
                      handleOk={handleOk}
                      confirmLoading={confirmLoading}
                      rowData={rowData}
            />
        </div>
    )
        ;
};

export default Index;